package com.crayon2f.test.thread;

import lombok.AllArgsConstructor;

import java.util.Optional;
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * Created by feifan.gou@gmail.com on 2020/12/2 16:33.
 */
public class CyclicBattierDemo2 {


    @AllArgsConstructor
    private static class Soldier implements Runnable {

        private final int number;
        private final CyclicBarrier cyclicBarrier;

        @Override
        public void run() {

            Optional.ofNullable(cyclicBarrier)
                    .ifPresent(ths -> {
                        try {
                            int await = ths.await();
                            Thread.sleep(Math.abs(new Random().nextInt() % 10000));
                            System.out.printf("I'm Number-%d, await = %d%n", number, await);
                        } catch (InterruptedException | BrokenBarrierException e) {
                            e.printStackTrace();
                        }
                    });
        }
    }

    @AllArgsConstructor
    private static class General implements Runnable {

        private final int soldiers;

        @Override
        public void run() {

            System.out.printf("%s名壮士已经集合完毕%n", soldiers);
        }
    }

    public static void main(String[] args) {

        int N = 20;
        Thread[] soldiers = new Thread[N];
        CyclicBarrier cyclicBarrier = new CyclicBarrier(N, new General(N));
        for (int i = 0; i < N; i++) {
            soldiers[i] = new Thread(new Soldier(i + 1, cyclicBarrier));
            soldiers[i].start();
        }
    }

}
